package org.jeecg.modules.business.third.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTaskMaterial;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskMaterialService;
import org.jeecg.modules.business.third.service.IMesStatusService;
import org.jeecg.modules.business.third.service.IThirdCommonService;
import org.jeecg.modules.business.warehouse.entity.WmsInReceiptTaskMaterial;
import org.jeecg.modules.business.warehouse.service.IWmsInReceiptTaskMaterialService;
import org.jeecg.modules.dock.config.JsonUtils;
import org.jeecg.modules.dock.entity.mes.request.*;
import org.jeecg.modules.dock.entity.mes.response.MesBaseResponseVO;
import org.jeecg.modules.dock.service.MesDockingRepeaterService;
import org.jeecg.modules.flow.sys.constant.FlowConstant;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/*
 * 项目名称:    wms-server-jeecg
 * 接口描述:    mes任务同步整合接口
 * 创建人员:    zhaojun
 * 创建时间:    2023-10-17
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MesStatusServiceImpl<T> implements IMesStatusService<T> {

    private final IThirdCommonService thirdCommonService;
    private final IWmsInReceiptTaskMaterialService wmsInReceiptTaskMaterialService;
    private final IWmsOutReceiptTaskMaterialService wmsOutReceiptTaskMaterialService;
    private final MesDockingRepeaterService mesDockingRepeaterService;

    @Override
    public boolean warehouse(String taskId, String receiptId, Integer status, T data) {
        log.info("开始同步入库任务状态，请求参数：taskId:{},receiptId:{},status:{},data:{}", taskId, receiptId, status
                , ObjectUtils.isEmpty(data) ? "无信息" : JsonUtils.toJson(data));
        AtomicBoolean result = new AtomicBoolean(true);

        Integer type = null;
        String taskType = "";
        if (StringUtils.isNotBlank(receiptId)) {
            type = 1;
        } else {
            type = 2;
        }
        if (ObjectUtils.isEmpty(status)) {
            throw new JeecgBootException("任务状态不能为空");
        }
        MesBaseRequestVO request = new MesBaseRequestVO();
        Map<String, Object> map = thirdCommonService.warehouseReceiptMaterialVoes(taskId, receiptId, type);
        String taskStatus = "";
        if (status == 1 || status == 3) {
            taskStatus = "TASK_STARTED";
            if (status == 3) {
                taskType = "ZJ-STOCK-KQ";
            }
        } else {
            taskStatus = "SEND_MATERIAL_FINISHED";
        }

        Map<String, Class> classMap = new HashMap<>();

        switch (map.get("documentType").toString()) {
            //        3	刻痕入库(原卷)
            case "R03":
                classMap.put("R03", ScoringStorageOrScratchRequestVO.class);
                break;
            //        5	刻痕退料(原卷)
            case "R05":
                classMap.put("R05", ScoringReturnOrScratchRequestVO.class);
                break;
            //        7	纵剪退料(原卷)
            case "R07":
                classMap.put("R07", TheMaterialIsWithdrawnByLongitudinalShearingRequestVO.class);
                break;
            //        08	纵剪叫纸筒(纸筒)
            case "R08":
                classMap.put("R08", VerticalCuttingIsCalledPaperTubeRequestVO.class);
                break;
            //        09	纵横剪退纸筒(纸筒)
            case "R09":
                classMap.put("R09", VerticalAndHorizontalCuttingRequestVO.class);
                break;
            //        12	纵剪入库(条料)
            case "R12":
                classMap.put("R12", LongitudinalShearStorageRequestVO.class);
                break;
            //        16	包装退料(条料)
            case "R16":
                classMap.put("R16", PackagingLineReturnRequestVO.class);
                break;
            //        18	叠片退料
            case "R18":
                classMap.put("R18", LaminationReturnRequestVO.class);
                break;
            //        23	叠片退料(辅材)
            case "R23":
                classMap.put("R23", LaminationReturnRequestVO.class);
                break;
            //        24	采购入库(辅材)
            case "R24":
                classMap.put("R24", LaminatedAuxiliaryMaterialReturnRequestVO.class);
                break;
            //        25	叠片报产(铁心)
            case "R25":
                classMap.put("R25", FinishedProductWarehousingIronRequestVO.class);
                break;
            //        26	包装入库(定尺)
            case "R26":
                classMap.put("R26", FinishedProductWarehousingScaleRequestVO.class);
                break;
            //        31	纵横剪退钢筒
            case "R31":
                classMap.put("R31", ReturnSteelBarrelRequestVO.class);
                break;
            //        35	生产入库(超大卷)
            case "R35":
                classMap.put("R35", SCStockSuperRequestVO.class);
                break;
            default:
                throw new JeecgBootException("未匹配类型，请重新核对");
        }

        Optional<String> first = classMap.keySet().stream().findFirst();

        List<WmsInReceiptTaskMaterial> taskMaterials = wmsInReceiptTaskMaterialService.list(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>().eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, map.get("taskId").toString()));
        Optional<WmsInReceiptTaskMaterial> taskMaterial = taskMaterials.stream().filter(t -> StringUtils.isNotBlank(t.getExtraText())).findFirst();
        if (taskMaterial.isPresent()) {
            MesBaseRequestVO vo = (MesBaseRequestVO) JSONObject.parseObject(taskMaterial.get().getExtraText(), classMap.get(first.get()));
            request.setTaskCode(vo.getTaskCode());
            request.setOperateTime(new Date());
            request.setTaskType(StringUtils.isBlank(taskType) ? vo.getTaskType() : taskType);
            request.setTaskStatus(taskStatus);
            request.setSite(vo.getSite());
            request.setOperateReason(vo.getOperateReason());
            request.setOperatorName(vo.getOperatorName());
            request.setLineName(vo.getLineName());
            request.setRemark(vo.getRemark());
            if (ObjectUtils.isNotEmpty(data)) {
                String s = data.toString();
                if (s.startsWith("[")) {
                    request.setData(data);
                } else {
                    request.setData(Arrays.asList(data));
                }
            }
            MesBaseResponseVO mesBaseResponseVO = mesDockingRepeaterService.updateStatus(request);

            if (ObjectUtils.isNotEmpty(mesBaseResponseVO)) {
                if (FlowConstant.ERROR.equals(mesBaseResponseVO.getTarget())) {
                    result.set(false);
                }
            } else {
                result.set(false);
            }
        } else {
            log.error("入库无mes的请求参数,无法同步任务状态");
            result.set(false);
        }


        log.info("结束同步入库任务状态");
        return result.get();
    }

    @Override
    public boolean outbound(String taskId, String receiptId, Integer status, T data) {
        log.info("开始出库入库任务状态，请求参数：taskId:{},receiptId:{},status:{},data:{}", taskId, receiptId, status
                , ObjectUtils.isEmpty(data) ? "无信息" : JsonUtils.toJson(data));
        String taskStatus = "";
        String taskType = "";
        if (status == 1 || status == 3) {
            taskStatus = "TASK_STARTED";
            if (status == 3) {
                taskType = "BZ-TAKE-KQ";
            }
        } else {
            taskStatus = "SEND_MATERIAL_FINISHED";
        }
        Integer type = null;
        if (StringUtils.isNotBlank(receiptId)) {
            type = 1;
        } else {
            type = 2;
        }
        AtomicBoolean result = new AtomicBoolean(true);
        Map<String, Object> map = thirdCommonService.outboundReceiptMaterialVoes(taskId, receiptId, type);
        MesBaseRequestVO request = new MesBaseRequestVO();
        Map<String, Class> classMap = new HashMap<>();
        switch (map.get("documentType").toString()) {
            //        4	刻痕叫料(原卷)
            case "C04":
                classMap.put("C04", ScoringReturnOrScratchRequestVO.class);
                break;
            //        6	纵剪叫料(原卷)
            case "C06":
                classMap.put("C06", SlittingIsCalledMaterialRequestVO.class);
                break;
            //        15	包装叫料(条料)
            case "C15":
                classMap.put("C15", PackagingLineMaterialOrderingRequestVO.class);
                break;
            //        22	叠片叫料(辅材)
            case "C22":
                classMap.put("C22", LaminationCallRequestVO.class);
                break;
            //        40	纵剪叫托盘(托盘)
            case "C40":
                classMap.put("C40", TheSlittingIsCalledATrayRequestVO.class);
                break;
            //        43	条料横剪叫料
            case "C43":
                classMap.put("C43", CrossShearCallMaterialRequestVO.class);
                break;
            case "C13":
                classMap.put("C13", TransverseShearCallMaterialPlateRequestVO.class);
                break;
            default:
                throw new JeecgBootException("未匹配类型，请重新核对");
        }

        List<WmsOutReceiptTaskMaterial> taskMaterials = wmsOutReceiptTaskMaterialService.list(new LambdaQueryWrapper<WmsOutReceiptTaskMaterial>().eq(WmsOutReceiptTaskMaterial::getWmsOutReceiptTaskId, map.get("taskId").toString()));
        Optional<WmsOutReceiptTaskMaterial> taskMaterial = taskMaterials.stream().filter(t -> StringUtils.isNotBlank(t.getExtraText())).findFirst();
        if (taskMaterial.isPresent()) {
            Optional<String> first = classMap.keySet().stream().findFirst();
            MesBaseRequestVO vo = (MesBaseRequestVO) JSONObject.parseObject(taskMaterial.get().getExtraText(), classMap.get(first.get()));
            request.setTaskCode(vo.getTaskCode());
            request.setOperateTime(new Date());
            request.setTaskType(StringUtils.isBlank(taskType) ? vo.getTaskType() : taskType);
            request.setTaskStatus(taskStatus);
            request.setSite(vo.getSite());
            request.setOperateReason(vo.getOperateReason());
            request.setOperatorName(vo.getOperatorName());
            request.setLineName(vo.getLineName());
            request.setRemark(vo.getRemark());
            if (ObjectUtils.isNotEmpty(data)) {
                if (data instanceof List || data.getClass().isArray()) {
                    request.setData(data);
                } else {
                    request.setData(Arrays.asList(data));
                }
            }

            MesBaseResponseVO mesBaseResponseVO = mesDockingRepeaterService.updateStatus(request);

            if (ObjectUtils.isNotEmpty(mesBaseResponseVO)) {
                if (FlowConstant.ERROR.equals(mesBaseResponseVO.getTarget())) {
                    result.set(false);
                }
            } else {
                result.set(false);
            }
        } else {
            log.error("出库无mes的请求参数,无法同步任务状态");
            result.set(false);
        }

        log.info("结束出库入库任务状态");

        return result.get();
    }
}
